import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2022-12-31
 * Time:19:33
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取账号密码
        //用户名可能存在中文，所以需要采用utf8
        req.setCharacterEncoding("utf-8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if(username==null||username.equals("")||password==null||password.equals("")){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或者密码为空！登陆失败！");
            return;
        }
        //查询数据库
        UserDao userDao=new UserDao();
        User user=userDao.selectByName(username);
        if(user==null||!user.getPassword().equals(password)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或者密码错误！登陆失败！");
            return;
        }
        //正确的创建一个会话对象
        HttpSession session=req.getSession(true);
        //会话保存一下user
        session.setAttribute("user",user);
        //响应一个重定向报文
        resp.sendRedirect("blog.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取会话
        HttpSession session=req.getSession(false);
        if(session==null){
            //没有会话
            resp.setStatus(403);
            return;
        }
        User user=(User)session.getAttribute("user");
        if(user==null){
            resp.setStatus(403);
            return;
        }
        //成功之后
        resp.setStatus(200);
    }
}
